<?php

namespace addons\mplogin\model;

use think\Model;
use think\Request;

class Key extends Model
{
    // 表名
    protected $name = 'mplogin_key';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected $error='';

    // 追加属性
    protected $append = [
        "state_text"
    ];

    public function getStateAttr(&$value, $item)
    {
        $item['createtime'] + self::timeout() * 60 < time() && $value = -1;
        $value == 1 && strlen($item['login_token']) > 10 && $value = 2;
        return $value;
    }

    private static function timeout()
    {
        $conf = get_addon_config("mplogin");
        return (isset($conf['timeout']) && $conf['timeout']) > 0 ? $conf['timeout'] : 3;
    }

    public function getStateTextAttr($value, $item)
    {
        $item['createtime'] + self::timeout() * 60 < time() && $item['state'] = -1;
        ($item['state'] == 1 && strlen($item['login_token']) > 10) && $item['state'] = 2;
        $status = [-3 => "请先关注公众号", -2 => "请绑定账号后,重新扫码", -1 => '操作超时', 0 => '未扫码', 1 => '已扫码', 2 => "登录成功"];
        return $status[$item['state']];
    }

    public static function setKey($cli = 'admin')
    {
        $unid = uniqid();
        $ip = Request::instance()->ip();
        session_start();
        $session_id = session_id();
        $temp_key = md5($session_id . $ip . $unid . $cli);
        return self::create([
            "key"        => $temp_key,
            "state"      => 0,
            "session_id" => $session_id,
            "salt"       => $unid,
            "createtime" => time(),
            "cli"        => $cli,
            "ip"         => $ip
        ]);
    }

   public static  function keyError(){
        return self::$error;
   }

    public static function getKey($key)
    {
        return self::get(["key" => $key]);
    }

    public static function getToken($token)
    {
        return self::get(["login_token" => $token]);
    }

    public static function checkToken($token) //验证登陆是否安全
    {
        $item = self::getToken($token);
        $ip = Request::instance()->ip();
        !session_id() && session_start();
        $token == md5($item->salt . $ip . session_id() . $item->cli) ? true : false;
        if($token){
            return true;
        }else{
            self::$error='登录存在风险,请用其他方式登录';
            return false;
        }

    }
}
